#!/usr/bin/bash
<<!
mysql 物理备份脚本
工具：xtrabackup 2.3.6
备份策略：周日完整备份 周一、二、四、五增量备份 周三、六差异备份
1、完全后台执行
2、备份完整
3、日志记录
4、历史数据的处理
!

dbUser="root"
dbPasswd="QianFeng@123"
backCMD="/usr/bin/innobackupex"
backDir="/backup"
logPath="/var/log/backup.log"
# 定义规则数组 0 完整备份 1 增量备份 2 差异备份
# 数组的值是备份的方式，数组的下标是星期几
rule=(0 1 1 2 1 1 2)
#     0 1 2 3 4 5 6
datetime=$(date +%w)

full(){
    mv $logPath $backDir
    tar cvzf /tmp/mysql_back_`date +%F`.tar.gz "$backDir" && \
    rm -rf $backDir
    mkdir -p $backDir/{full,incr,diff}
    $backCMD --user=$dbUser --password=$dbPasswd $backDir/full
    echo "full `ls $backDir/full |tail -n 1`" >> $logPath
    
}
other(){
    # $1 incr|diff 备份的类型
    # $2 需要基于的完整路径
    $backCMD --user=$dbUser --password=$dbPasswd --incremental $backDir/$1 --incremental-basedir=$2
    echo "$3 `ls $backDir/$3 |tail -n 1`" >> $logPath
}

case ${rule[$datetime]} in # ${rule[5]}
0)
    full 
    ;;
1)
    type=$(tail -n 1 $logPath|awk '{print $1}') # 获取上一次备份的类型
    time=$(tail -n 1 $logPath|awk '{print $2}') # 获取上一次备份的目录
    other incr $backDir/$type/$time incr
            # /backup/full/2022-05-22_00-00-05
    ;;
2)
    time=$(grep full $logPath|awk '{print $2}')
    other diff $backDir/full/$time diff
    ;;
esac
